﻿using JNPF.Utils;
using System;
using System.Data;
using System.Data.SqlClient;

namespace JNPF.Data.Util
{
    /// <summary>
    /// 数据库访问扩展
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// </summary>
    public static class DbBulkCopy
    {
        /// <summary>
        /// 大批量数据插入,返回成功插入行数
        /// </summary>
        /// <param name="cnn"></param>
        /// <param name="table"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public static int SqlBulkCopy(this IDbConnection cnn, DataTable table, IDbTransaction transaction = null)
        {
            if (table.Rows.Count == 0) return 0;
            if (cnn.State != ConnectionState.Open)
                cnn.Open();
            DatabaseType dbType = cnn.ToString().ToDatabaseType();
            switch (dbType)
            {
                case DatabaseType.SqlServer:
                    SqlBulkCopy(table, cnn, transaction);
                    break;
                case DatabaseType.Oracle:
                    OracleBulkCopy(table, cnn, transaction);
                    break;
                case DatabaseType.MySql:
                    MySqlBulkCopy(table, cnn, transaction);
                    break;
            }
            return table.Rows.Count;
        }
        private static void SqlBulkCopy(DataTable table, IDbConnection cnn, IDbTransaction transaction = null)
        {
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConfigurationHelper.GetDbConnection("JNPF_DB_Default:ConnectionString"), SqlBulkCopyOptions.UseInternalTransaction))
            {
                bulkCopy.DestinationTableName = table.TableName;
                bulkCopy.NotifyAfter = table.Rows.Count;
                bulkCopy.WriteToServer(table);
                bulkCopy.Close();
            }
        }
        private static void OracleBulkCopy(DataTable table, IDbConnection cnn, IDbTransaction transaction = null)
        {
            throw new Exception("不支持Oracle");
        }
        private static void MySqlBulkCopy(DataTable table, IDbConnection cnn, IDbTransaction transaction = null)
        {
            throw new Exception("不支持MySql");
        }
    }
}
